package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author DBX
 * @effect
 * @date 2021/8/31 0031 - 19:27
 */
public class Server2 {
    private ServerSocket serverSocket;
    private Socket socket;

    public Server2(){
        try {
            System.out.println("服务启动中");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务启动成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        while (true){
            try {
                System.out.println("等待连接");
                socket = serverSocket.accept();
                System.out.println(socket.getInetAddress().getHostAddress()+"连接成功");
                ClientHandler ch = new ClientHandler(socket);
                Thread t = new Thread(ch);
                t.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        Server2 s = new Server2();
        s.start();
    }
    class ClientHandler implements Runnable{
        private Socket socket;
        private String host;
        public ClientHandler(Socket socket){
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
        }
        BufferedReader br = null;
        String message = null;
        @Override
        public void run() {
            try {
                br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
                while (((message = br.readLine())!=null)){
                    System.out.println(host+"说："+message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}
